/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2019/5/29 20:54
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.aurora.core.bean;

import com.hyacinth.aurora.aop.annotation.Aspect;
import com.hyacinth.aurora.core.ClassHelper;
import com.hyacinth.aurora.core.InstanceFactory;
import com.hyacinth.aurora.core.exception.BeansException;
import com.hyacinth.aurora.core.exception.InitializationError;
import com.hyacinth.aurora.core.exception.SingleClassInstanceException;
import com.hyacinth.aurora.core.init.Initialization;
import com.hyacinth.aurora.ioc.annotation.Bean;
import com.hyacinth.aurora.ioc.annotation.Service;
import com.hyacinth.aurora.mvc.annotation.AuroraAction;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;

/**
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public final class BeanManager extends Initialization {

    // 单例模式
    private BeanManager() throws SingleClassInstanceException {
        super();
    }

    private BeanFactory beanFactory;

    /**
     * 初始化bean
     */
    @Override
    protected void doInit() throws Exception {
        // 初始化bean工厂
        beanFactory = InstanceFactory.getBeanFactory();
        // 获取应用包路径下所有的类
        List<Class<?>> classList = ClassHelper.getClassList();
        for (Class<?> cls : classList) {
            // 处理带有 Bean/Service/Action/Aspect 注解的类
            if (isAuroraBeanInstance(cls)) {
                // 创建 Bean 实例
                Object beanInstance = cls.newInstance();
                // 将Bean实例放入BeanMap中[键为Bean实例名，值为Bean实例]
                beanFactory.register(cls.getSimpleName(), beanInstance);
            }
        }
    }

    @Override
    protected void doDestroy() throws Exception {
        releaseBean();
    }

    /**
     * 判断类是否为bean实例
     * @param cls 类
     * @return
     */
    private boolean isAuroraBeanInstance(Class<?> cls){
        return cls.isAnnotationPresent(Bean.class) ||
                cls.isAnnotationPresent(Service.class) ||
                cls.isAnnotationPresent(AuroraAction.class) ||
                cls.isAnnotationPresent(Aspect.class);
    }

    /**
     * get bean
     */
    public Object getBean(String name) throws BeansException{
        return beanFactory.getBean(name);
    }

    public <T> T getBean(Class<T> beanType) throws BeansException {
        return beanFactory.getBean(beanType);
    }

    public <T> T getBean(String name, Class<T> beanType) throws BeansException {
        return beanFactory.getBean(name, beanType);
    }

    public Map<String, Object> getBeanMap() {
        return beanFactory.getBeanMap();
    }

    /**
     * release all beans
     */
    private void releaseBean(){
        beanFactory.releaseBean();
    }

}
